package org.vincen.springapp.util;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

@Repository("jPAUtil")
public class JPAUtil {

	@PersistenceContext(unitName = "springjpa")
	private EntityManager entityManager;

	/**
	 * 通用查询方法，可以携带若干查询参数
	 * 
	 * @param clazz
	 *            需要查询的类
	 * @param map
	 *            查询参数
	 * @param firstResult
	 *            当前页页码
	 *            如果页码是-1，则默认为不分页查询
	 * @param maxResults
	 *            每页最大显示的记录数量
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T extends Object> List<T> findCollection(Class<T> clazz,
			Map<String, Object> map, int firstResult, int maxResults) {
		StringBuilder builder = new StringBuilder();
		// flag第一个数据添加标志
		boolean flag = false;
		Query query = null;
		// 构建查询语句
		builder.append("from ");
		builder.append(clazz.getSimpleName());
		builder.append(" t ");
		// 构建查询条件
		if (map != null && map.size() != 0) {
			builder.append(" t where ");
			Set<String> keys = map.keySet();
			for (String key : keys) {
				if (flag) {
					builder.append(" and ");
				}
				builder.append("t.");
				builder.append(key);
				builder.append(" = ");
				builder.append(":");
				builder.append(key);
				if (map.size() > 1) {
					flag = true;
				}
			}
			query = entityManager.createQuery(builder.toString());
			for (String key : keys) {
				query.setParameter(key, map.get(key));
			}
		}else {
			query = entityManager.createQuery(builder.toString());
		}
		// 做分页判断
		if (firstResult != -1) {
			query.setFirstResult(firstResult);
			query.setMaxResults(maxResults);
		}
		return query.getResultList();
	}
}
